package com.qlylkj.lbk.ui.user.authentication

import android.view.View
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import com.forest.core.etx.*
import com.forest.core.util.RegularUtil
import com.forest.core.widget.dialog.FDialog
import com.forest.core.widget.dialog.FDialogInterface
import com.forest.core.widget.dialog.Options
import com.jeremyliao.liveeventbus.LiveEventBus
import com.qlylkj.lbk.R
import com.qlylkj.lbk.app.Constant
import com.qlylkj.lbk.app.PreferenceHelper
import com.qlylkj.lbk.base.BaseVMActivity
import com.qlylkj.lbk.model.bean.Company
import com.qlylkj.lbk.model.event.LiveEvent
import com.qlylkj.lbk.ui.photo.PhotoPagerAdapter
import com.qlylkj.lbk.ui.search.SearchActivity
import com.qlylkj.lbk.ui.setting.AgreementActivity
import com.qw.photo.CoCo
import com.qw.photo.callback.GetImageCallBack
import com.qw.photo.pojo.PickResult
import kotlinx.android.synthetic.main.activity_indentity_auth.*
import kotlinx.android.synthetic.main.dialog_photo_pager.*
import kotlinx.android.synthetic.main.layout_toolbar.*
import java.io.File

class IdentityAuthActivity : BaseVMActivity<IdentityAuthViewModel>() {

    companion object {
        const val PERSONAL_AUTHENTICATION = 1
        const val COMPANY_AUTHENTICATION = 2
        const val COMMISSION_PROVE = 3
        const val WAIT_FOR_REVIEW = 4
    }

    private val options = mutableMapOf<String, Any>()

    override fun providerVMClass() = IdentityAuthViewModel::class.java

    override fun setLayoutId() = R.layout.activity_indentity_auth

    override fun initView() {
        toolbar.setNavigationOnClickListener { finish() }
        toolbarTitle.text = getString(R.string.activity_identity_authentication)
        identityCardFrontImage.setOnClickListener(onClickListener)
        identityCardContraryImage.setOnClickListener(onClickListener)
        personalAuthenticationNext.setOnClickListener(onClickListener)
        companyBusinessLicenseImage.setOnClickListener(onClickListener)
        companyNameText.setOnClickListener(onClickListener)
        companyAuthenticationNext.setOnClickListener(onClickListener)
        commissionProveImage.setOnClickListener(onClickListener)
        commissionProveTemplateImage.setOnClickListener(onClickListener)
        commissionProveNext.setOnClickListener(onClickListener)
        authenticationAgreementText.setOnClickListener(onClickListener)
        toMine.setOnClickListener(onClickListener)
        changeAuthenticationStep(PERSONAL_AUTHENTICATION)
        LiveEventBus.get(LiveEvent.SELECT_COMPANY_KEY, Company::class.java)
            .observeSticky(this, Observer<Company> {
                it?.run {
                    companyNameText.text = companyName
                    options["companyName"] = companyName
                    options["comsumsId"] = id
                }
            })
    }

    override fun initData() {

    }

    override fun startObserve() {
        super.startObserve()
        mViewModel.apply {
            uploadUiState.observe(this@IdentityAuthActivity, Observer { uiModel ->
                uiModel?.run {
                    showError?.let {
                        toast(it)
                    }
                    uploadUrl?.let {
                        when(type){
                            Constant.UploadType.TYPE_IDENTITY_CARD_FRONT -> options["idcardFrontImg"] = it
                            Constant.UploadType.TYPE_IDENTITY_CARD_CONTRARY -> options["idcardBehindImg"] = it
                            Constant.UploadType.TYPE_COMPANY_BUSINESS_LICENSE -> options["businessLicenseImg"] = it
                            Constant.UploadType.TYPE_COMMISSION_PROVE -> options["authorization"] = it
                            else -> {}
                        }
                    }
                }
            })
            uiState.observe(this@IdentityAuthActivity, Observer { uiModel ->
                uiModel?.run {
                    showError?.let {
                        toast(it)
                    }
                    if(identityAuthSuccess){
                        toast("认证信息已提交,请等待审核。")
                        finish()
                    }
                }
            })
        }
    }


    private fun changeAuthenticationStep(step: Int) {
        (PERSONAL_AUTHENTICATION == step).let {
            personalAuthenticationStep.isSelected = it
            personalAuthenticationLayout.isVisible = it
        }
        (COMPANY_AUTHENTICATION == step).let {
            companyAuthenticationStep.isSelected = it
            companyAuthenticationLayout.isVisible = it
        }
        (COMMISSION_PROVE == step).let {
            commissionProveStep.isSelected = it
            commissionProveLayout.isVisible = it
        }
        (WAIT_FOR_REVIEW == step).let {
            waitForReviewStep.isSelected = it
            waitForReviewLayout.isVisible = it
        }
    }

    private val onClickListener = View.OnClickListener {
        when (it.id) {
            R.id.identityCardFrontImage -> uploadIdentityCardFront()
            R.id.identityCardContraryImage -> uploadIdentityCardContrary()
            R.id.personalAuthenticationNext -> personalAuthentication()
            R.id.companyBusinessLicenseImage -> uploadCompanyBusinessLicense()
            R.id.companyNameText -> selectCompany()
            R.id.companyAuthenticationNext -> companyAuthentication()
            R.id.commissionProveImage -> uploadCommissionProve()
            R.id.commissionProveTemplateImage -> lookCommissionProveTemplate()
            R.id.commissionProveNext -> commissionProve()
            R.id.authenticationAgreementText -> lookAuthenticationAgreement()
            R.id.toMine -> toMine()
        }
    }

    private fun showPhotoPagerDialog(imageList: MutableList<Any>) {
        FDialog.newInstance().apply {
            options = Options().apply {
                isTransparent = true
                layoutRes = R.layout.dialog_photo_pager
            }
            setOnDismissListener(object : FDialogInterface.OnDismissListener {
                override fun onDismiss(dialog: FDialogInterface) {

                }
            })
            setOnBuilderViewListener(object : FDialogInterface.OnBuilderViewListener {
                override fun onBuilderView(
                    dialog: FDialogInterface,
                    view: View,
                    layoutRes: Int
                ) {
                    photoPagerViewPager.apply {
                        adapter = PhotoPagerAdapter({ dialog.dismiss() }, imageList)
                    }
                }
            })
            show(supportFragmentManager, "photoPager")
        }
    }

    private fun uploadIdentityCardFront() {
        val fileDir = getCacheFile("upload")
        val targetFile = File(fileDir, "identityCardFront.png")
        CoCo.with(this)
            .pick()
            .targetFile(targetFile)
            .applyWithDispose()
            .start(object : GetImageCallBack<PickResult> {

                override fun onSuccess(data: PickResult) {
                    identityCardFrontImage.load(this@IdentityAuthActivity, data.originUri)
                    data.targetFile?.let {
                        mViewModel.uploadFile(Constant.UploadType.TYPE_IDENTITY_CARD_FRONT,it)
                    }
                }

                override fun onFailed(exception: Exception) {
                    toast("选择异常: $exception")
                }
            })
    }

    private fun uploadIdentityCardContrary() {
        val fileDir = getCacheFile("upload")
        val targetFile = File(fileDir, "identityCardContrary.png")
        CoCo.with(this)
            .pick()
            .targetFile(targetFile)
            .applyWithDispose()
            .start(object : GetImageCallBack<PickResult> {

                override fun onSuccess(data: PickResult) {
                    identityCardContraryImage.load(this@IdentityAuthActivity, data.originUri)
                    data.targetFile?.let {
                        mViewModel.uploadFile(Constant.UploadType.TYPE_IDENTITY_CARD_CONTRARY,it)
                    }
                }

                override fun onFailed(exception: Exception) {
                    toast("选择异常: $exception")
                }
            })
    }

    private fun personalAuthentication() {
        val realName = personalNameEdit.toTrim()
        val identityCardCode = identityCardCodeEdit.toTrim()
        if(!options.containsKey("idcardFrontImg")){
            toast("请上传身份证正面照片")
            return
        }
        if(!options.containsKey("idcardBehindImg")){
            toast("请上传身份证反面照片")
            return
        }
        if(!RegularUtil.isName(realName)){
            toast("请输入真实姓名")
            return
        }
        if(!RegularUtil.isIdCard(identityCardCode)){
            toast("请输入正确的身份证号码")
            return
        }
        options["userid"] = PreferenceHelper.userId
        options["realname"] = realName
        options["idcardCode"] = identityCardCode
        changeAuthenticationStep(COMPANY_AUTHENTICATION)
    }

    private fun uploadCompanyBusinessLicense() {
        val fileDir = getCacheFile("upload")
        val targetFile = File(fileDir, "companyBusinessLicense.png")
        CoCo.with(this)
            .pick()
            .targetFile(targetFile)
            .applyWithDispose()
            .start(object : GetImageCallBack<PickResult> {

                override fun onSuccess(data: PickResult) {
                    companyBusinessLicenseImage.load(this@IdentityAuthActivity, data.originUri)
                    data.targetFile?.let {
                        mViewModel.uploadFile(Constant.UploadType.TYPE_COMPANY_BUSINESS_LICENSE,it)
                    }
                }

                override fun onFailed(exception: Exception) {
                    toast("选择异常: $exception")
                }
            })
    }

    private fun selectCompany(){
        startKtxActivity<SearchActivity>(value = SearchActivity.SELECT_COMPANY to true)
    }

    private fun companyAuthentication() {
        val companyPosition = companyPositionEdit.toTrim()
        val contactWay = contactWayEdit.toTrim()
        if(!options.containsKey("businessLicenseImg")){
            toast("请上传企业营业执照")
            return
        }
        if(!options.containsKey("companyName")){
            toast("请选择要认证的公司")
            return
        }
        if(companyPosition.isEmpty()){
            toast("请填写你在公司所担任的职位")
            return
        }
        if(contactWay.isEmpty()){
            toast("请填写公司负责人联系方式")
            return
        }
        options["userPosition"] = companyPosition
        options["cphone"] = contactWay
        changeAuthenticationStep(COMMISSION_PROVE)
    }

    private fun uploadCommissionProve() {
        val fileDir = getCacheFile("upload")
        val targetFile = File(fileDir, "commissionProve.png")
        CoCo.with(this)
            .pick()
            .targetFile(targetFile)
            .applyWithDispose()
            .start(object : GetImageCallBack<PickResult> {

                override fun onSuccess(data: PickResult) {
                    commissionProveImage.load(this@IdentityAuthActivity, data.originUri)
                    data.targetFile?.let {
                        mViewModel.uploadFile(Constant.UploadType.TYPE_COMMISSION_PROVE,it)
                    }
                }

                override fun onFailed(exception: Exception) {
                    toast("选择异常: $exception")
                }
            })
    }

    private fun lookCommissionProveTemplate() {
            showPhotoPagerDialog(mutableListOf(R.mipmap.bg_commission_prove_template))
    }

    private fun commissionProve() {
        if(!options.containsKey("authorization")){
            toast("请上传委托证明书")
            return
        }
        changeAuthenticationStep(WAIT_FOR_REVIEW)
        mViewModel.identityAuth(options)
    }

    private fun lookAuthenticationAgreement() {
        startKtxActivity<AgreementActivity>(value = AgreementActivity.AGREEMENT_TYPE to AgreementActivity.AGREEMENT_AUTH)
    }

    private fun toMine() {
        finish()
    }

}